package tlias.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tlias.mapper.EmpExprMapper;
import tlias.mapper.EmpMapper;
import tlias.service.EmpLogService;
import tlias.service.EmpService;
import tlias.pojo.*;

import java.time.LocalDate;
import java.util.List;

@Slf4j
@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;
    @Autowired
    private EmpLogService empLogService;
    public EmpServiceImpl(EmpMapper empMapper, EmpExprMapper empExprMapper , EmpLogService empLogService) {
        this.empLogService = empLogService;
        this.empMapper = empMapper;
        this.empExprMapper = empExprMapper;
    }
    public PageResult<Emp> getAllEmps(EmpsRequestParam param) {
        PageHelper.startPage(param.getPage(),param.getPageSize());
        Page<Emp> page1 = (Page<Emp>) empMapper.getAllEmps(param);
        return new PageResult<>(page1.getTotal(), page1.getResult());
    }

    @Override
    public void delete(Integer[] ids) {
        empMapper.delete(ids);
        empExprMapper.deleteExpr(ids);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(Emp emp) {
        try {
            emp.setCreateTime(LocalDate.now().atStartOfDay());
            emp.setUpdateTime(LocalDate.now().atStartOfDay());
            List<EmpExpr> exprList = emp.getExprList();
            empMapper.add(emp);
            if (!exprList.isEmpty()) {
                exprList.forEach(expr -> expr.setEmpId(emp.getId()));
                empExprMapper.add(exprList);
            }
        } finally {
            empLogService.insert(new EmpLog(emp.getId(), LocalDate.now().atStartOfDay(), emp.toString()));
        }
    }

    @Override
    public Emp getById(Integer id) {
        return  empMapper.getById(id);
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(Emp emp) {
        empMapper.update(emp);
        List<EmpExpr> exprList = emp.getExprList();
        if (!exprList.isEmpty()) {
            empExprMapper.deleteExpr(new Integer[]{emp.getId()});
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));
            empExprMapper.add(exprList);
        }
    }
}
